package com.jason.apps.dashboard;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.apps.essentials.ConsumeWebService;
import com.apps.realtyportal.HomeActivity;
import com.apps.realtyportal.R;
import com.forimageandlist.SoldAdapter;
import com.google.android.maps.MapView;
import com.ipaulpro.afilechooser.utils.FileUtils;
import com.shanu.apps.details.ShowPropertyDetail;

public class ManageProperty extends SherlockFragmentActivity implements
		EditProperty.EditOnClickSelectedListener,
		AddProperty.AddOnClickSelectedListener {

	public static String Path = null;
	public static String DATE = null;

	public static Context appContext;
	ActionBar actionbar;

	SoldAdapter adapter;
	public static String strlat;
	public static String strlon;

	private static final int LOGOUT = 7;
	private static final int DASHBOARD = 8;

	private static final int VIEW_MAP = 5;
	private static final int VIEW_MAP_EDIT = 6;
	private MapView viewmpa;

	// public static OnClickSelectedListener mCallback;

	ConsumeWebService c;

	final static ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

	HashMap<String, String> map;
	private ListView list;
	SherlockFragmentActivity fa;

	static List<String> names = new ArrayList<String>();
	static List<Integer> ids = new ArrayList<Integer>();
	static List<String> email = new ArrayList<String>();

	public static final String KEY_ID = "property_id";
	public static final String KEY_NAME = "property_name";
	public static final String KEY_DESCRIPTION = "property_description";
	public static final String KEY_PRICE = "price";
	public static final String KEY_LATITUDE = "latitude";
	public static final String KEY_LONGITUDE = "longitude";
	public static final String KEY_ADDRESS = "address";
	public static final String KEY_TYPE = "type";
	public static final String KEY_IMAGE = "main_image";

	private static final int REQUEST_CODE = 1;
	private static final int REQUEST_BROWSEPANORAMA = 2;
	private static final int REQUEST_BROWSEAMMENITIES = 3;
	private static final int REQUEST_EDITPROPERTY = 4;
	private static final int AMMENITIES = 5;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.displayhere2);
		// appContext = getApplicationContext();

		// ActionBar
		actionbar = getSupportActionBar();
		actionbar.setDisplayHomeAsUpEnabled(true);
		actionbar.setDisplayShowTitleEnabled(false);
		actionbar.setLogo(R.drawable.logo3);
		adapter = new SoldAdapter(this, mylist);

		list = (ListView) findViewById(R.id.listViewProperty45);

		EditProperty firstFragment = new EditProperty();

		// In case this activity was started with special instructions from an
		// Intent,
		// pass the Intent's extras to the fragment as arguments
		// firstFragment.setArguments(getIntent().getExtras());

		// Add the fragment to the 'fragment_container' FrameLayout

		getSupportFragmentManager().beginTransaction()
				.add(R.id.fragment_container2, firstFragment).commit();

		// new Load().execute();

	}

	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		// menu.add(0, DASHBOARD, 0, "Logout")
		// .setTitle("Log out").setTitle("Go to Dashboard")
		// .setIcon(R.drawable.ic_action_overflow)
		// .setShowAsAction(
		// MenuItem.SHOW_AS_ACTION_IF_ROOM);
		//
		//
		//
		// return super.onCreateOptionsMenu(menu);

		SubMenu subMenu = menu.addSubMenu("Options");

		// subMenu.add("Logout").setIcon(R.drawable.logouticon);
		// subMenu.add("Go to Profile").setIcon(R.drawable.profile1);

		subMenu.add(0, 10, Menu.NONE, "Logout").setIcon(R.drawable.logouticon);
		subMenu.add(0, 15, Menu.NONE, "Back to Property List").setIcon(
				R.drawable.profile);

		MenuItem subMenu1Item = subMenu.getItem();
		subMenu1Item.setIcon(R.drawable.ic_action_overflow);
		subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			Intent intent = new Intent(this, HomeActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			startActivity(intent);

		case 10:
			// finish();
			startActivity(new Intent(getApplicationContext(),
					HomeActivity.class));
			HomeActivity.islogin=false;
		case 15:
			finish();

		}
		return super.onOptionsItemSelected(item);
	}

	public void displayList() {
		c = new ConsumeWebService();
		String data = c.getAllProperty();

		try {

			JSONArray array = new JSONArray(data);

			for (int i = 0; i < array.length(); i++) {
				map = new HashMap<String, String>();
				JSONObject e = array.getJSONObject(i);
				map.put("property_id", e.getString(KEY_ID));
				map.put("property_name", e.getString(KEY_NAME));
				map.put("property_description", e.getString(KEY_DESCRIPTION));
				map.put("price", e.getString(KEY_PRICE));
				map.put("latitude", e.getString(KEY_LATITUDE));
				map.put("longitude", e.getString(KEY_LONGITUDE));
				map.put("address", e.getString(KEY_ADDRESS));
				map.put("type", e.getString(KEY_TYPE));
				map.put("image", e.getString(KEY_IMAGE));
				map.put("name",
						e.getString("firstname") + " "
								+ e.getString("lastname"));
				map.put("selling_type", e.getString("selling_type"));

				names.add(e.getString("firstname") + " "
						+ e.getString("lastname"));
				ids.add(e.getInt("person_id"));
				email.add(e.getString("email_address"));

				mylist.add(map);
			}
		} catch (JSONException e) {
			Log.e("log_tag", "Error parsing data " + e.toString() + "diri jud");
		} finally {

		}
	}

	//POP UP MAP ADD PROPERTY
		public void popUpMap(View v){
			Intent i=new Intent(this,ViewMap.class);
			startActivityForResult(i, VIEW_MAP);
		}		
		
		public void EBrowseMap(View v){
			Intent i=new Intent(this,ViewMap.class);
			startActivityForResult(i, VIEW_MAP_EDIT);
		}		
		public void BrowsePic(View v) {
			Intent target = FileUtils.createGetContentIntent();
			Intent intent = Intent.createChooser(target,
					getString(R.string.chooser_title));

			try {
				startActivityForResult(intent, REQUEST_CODE);
			} catch (ActivityNotFoundException e) {
			}
		}

		public void BROWSEPANORAMA(View v) {
			Intent target = FileUtils.createGetContentIntent();
			Intent intent = Intent.createChooser(target,
					getString(R.string.chooser_title));

			try {
				startActivityForResult(intent, REQUEST_BROWSEPANORAMA);
			} catch (ActivityNotFoundException e) {
			}
		}

		public void BROWSEAMMENITIES(View v) {
			Intent target = FileUtils.createGetContentIntent();
			Intent intent = Intent.createChooser(target,
					getString(R.string.chooser_title));

			try {
				startActivityForResult(intent, REQUEST_BROWSEAMMENITIES);
			} catch (ActivityNotFoundException e) {
			}
		}

		public void EditBrowsePic(View v) {
			Intent target = FileUtils.createGetContentIntent();
			Intent intent = Intent.createChooser(target,
					getString(R.string.chooser_title));

			try {
				startActivityForResult(intent, REQUEST_EDITPROPERTY);
			} catch (ActivityNotFoundException e) {
			}
		}

		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			switch (requestCode) {
			
			case REQUEST_CODE:
				if (resultCode == RESULT_OK) {
					if (data != null) {
						final Uri uri = data.getData();

						try {
							Path = getRealPathFromURI(uri);

							AddProperty prop = (AddProperty) getSupportFragmentManager()
									.findFragmentById(R.id.fragment_container2);
							prop.setUrl(Path);

						} catch (Exception e) {
							Log.e("FileSelectorTestActivity",
									"File select error CREATEACCOUNT", e);
						}
					}

				}
				break;
			case REQUEST_BROWSEPANORAMA:
				if (resultCode == RESULT_OK) {
					if (data != null) {
						final Uri uri = data.getData();

						try {
							Path = getRealPathFromURI(uri);

							AddProperty prop = (AddProperty) getSupportFragmentManager()
									.findFragmentById(R.id.fragment_container2);
							prop.setUrlPanorama(Path);

						} catch (Exception e) {
							Log.e("FileSelectorTestActivity",
									"File select error PERSONDETAIL", e);
						}
					}

				}
				break;
			case REQUEST_BROWSEAMMENITIES:
				if (resultCode == RESULT_OK) {
					if (data != null) {
						final Uri uri = data.getData();

						try {
							Path = getRealPathFromURI(uri);

							AddProperty prop = (AddProperty) getSupportFragmentManager()
									.findFragmentById(R.id.fragment_container2);
							prop.setUrlAmmenities(Path);

						} catch (Exception e) {
							Log.e("FileSelectorTestActivity",
									"File select error PERSONDETAIL", e);
						}
					}

				}
				break;

			case REQUEST_EDITPROPERTY:
				
				if (resultCode == RESULT_OK) {
					if (data != null) {
						
						final Uri uri = data.getData();

						try {
							Path = getRealPathFromURI(uri);

							PropertyDetail prop = (PropertyDetail) getSupportFragmentManager()
									.findFragmentById(R.id.fragment_container2);
							prop.setUrl(Path);

						} catch (Exception e) {
							Log.e("FileSelectorTestActivity",
									"File select error PERSONDETAIL", e);
						}
					}

				}
				break;
				
			case VIEW_MAP:
				if (resultCode == RESULT_OK) {
					if (data != null) {
						
						AddProperty prop = (AddProperty) getSupportFragmentManager()
								.findFragmentById(R.id.fragment_container2);
						prop.setLongLat(data.getStringExtra("longitude"),data.getStringExtra("latitude"));
						
					}

				}
				break;

			case VIEW_MAP_EDIT:
			if (resultCode == RESULT_OK) {
				if (data != null) {
					
					PropertyDetail prop = (PropertyDetail) getSupportFragmentManager()
							.findFragmentById(R.id.fragment_container2);
					prop.setLongLat(data.getStringExtra("longitude"),data.getStringExtra("latitude"));
					
				}

			}
			break;
			
			}
		
			super.onActivityResult(requestCode, resultCode, data);
		}

	public String getRealPathFromURI(Uri contentUri) {
		String[] proj = { MediaStore.Images.Media.DATA };

		Cursor cursor = getContentResolver().query(contentUri, proj, null,
				null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);

	}

	/*
	 * @Override public void onArticleSelected(int position) {
	 * 
	 * PropertyDetail newFragment = new PropertyDetail(); Bundle args = new
	 * Bundle(); args.putInt(PropertyDetail.ARG_POSITION, position);
	 * newFragment.setArguments(args);
	 * 
	 * FragmentTransaction transaction =
	 * getSupportFragmentManager().beginTransaction();
	 * //transaction.replace(R.id.fragment_container2, newFragment);
	 * transaction.addToBackStack(null);
	 * 
	 * transaction.commit(); }
	 */

	public class Load extends AsyncTask<Void, Void, Void> {

		private final ProgressDialog dialog = new ProgressDialog(
				ManageProperty.this);

		protected void onPreExecute() {

			this.dialog.setMessage("Loading...");
			this.dialog.show();
		}

		protected Void doInBackground(final Void... unused) {

			try {
				displayList();

			} catch (Exception e) {
				Log.e("", "wala jud ma add", e);
			}
			return null;
		}

		protected void onPostExecute(Void result) {

			list.setAdapter(adapter);

			if (this.dialog != null) {
				this.dialog.dismiss();
			}
		}
	}

	public void onArticleSelected(View v, int position) {
		// TODO Auto-generated method stub
		PropertyDetail newFragment = new PropertyDetail();
		Bundle args = new Bundle();
		args.putInt(PropertyDetail.ARG_POSITION, position);
		newFragment.setArguments(args);

		FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();
		transaction.replace(R.id.fragment_container2, newFragment);
		transaction.addToBackStack(null);

		transaction.commit();
	}

	public void AddArticleSelected(View v, int position) {
		// TODO Auto-generated method stub
		AddProperty newFragment = new AddProperty();

		/*
		 * Bundle args = new Bundle(); //
		 * args.putInt(PropertyDetail.ARG_POSITION, position);
		 * newFragment.setArguments(args);
		 */

		FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();
		transaction.replace(R.id.fragment_container2, newFragment);
		transaction.addToBackStack(null);

		transaction.commit();
	}

	public void ShowDetailOnArticleSelected(View v, int position) {
		// TODO Auto-generated method stub
		ShowPropertyDetail newFragment = new ShowPropertyDetail();
		Bundle args = new Bundle();
		args.putInt(ShowPropertyDetail.ARG_POSITION, position);
		args.putString("running", "show");
		newFragment.setArguments(args);

		FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();
		transaction.replace(R.id.fragment_container2, newFragment);
		transaction.addToBackStack(null);

		transaction.commit();
	}

}